import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import * as colors from 'colors';
import * as moment from 'moment';
import { Between, DeleteResult, Like, Repository } from 'typeorm';
import { SortType } from '../../common/constants/common.constant';
import { LogAppender, LogLevel } from '../constants/log.constant';
import { LogEntity } from '../entities/log.entity';

@Injectable()
export class LogService {
  constructor(@InjectRepository(LogEntity) private readonly logRepository: Repository<LogEntity>) {}

  /**
   * Trace日志
   * @param appender 日志类别
   * @param message 日志内容
   * @param detail 详细内容
   */
  trace(appender: LogAppender, message: string, detail?: string) {
    console.log(colors.blue(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [TRACE] [${appender}] - ${message}`));
    this.create(LogLevel.trace, appender, message, detail);
  }

  /**
   * Debug日志
   * @param appender 系统日志类别
   * @param message 日志内容
   * @param detail 详细内容
   */
  debug(appender: LogAppender, message: string, detail?: string) {
    console.log(colors.yellow(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [${appender} - ${message}]`));
    this.create(LogLevel.debug, appender, message, detail);
  }

  /**
   * Info日志
   * @param appender 系统日志类别
   * @param message 日志内容
   * @param detail 详细内容
   */
  info(appender: LogAppender, message: string, detail?: string) {
    console.log(colors.green(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [${appender}] - ${message}`));
    this.create(LogLevel.info, appender, message, detail);
  }

  /**
   * Warn日志
   * @param appender 系统日志类别
   * @param message 日志内容
   * @param detail 详细内容
   */
  warn(appender: LogAppender, message: string, detail?: string) {
    console.log(colors.yellow(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] [${appender}] - ${message}`));
    this.create(LogLevel.warn, appender, message, detail);
  }

  /**
   * Error日志
   * @param appender 系统日志类别
   * @param message 日志内容
   * @param detail 详细内容
   */
  error(appender: LogAppender, message: string, detail?: string) {
    console.log(colors.red(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [${appender}] - ${message}`));
    this.create(LogLevel.error, appender, message, detail);
  }

  /**
   * Fatal日志
   * @param appender 系统日志类别
   * @param message 日志内容
   * @param detail 详细内容
   */
  fatal(appender: LogAppender, message: string, detail?: string) {
    console.log(colors.magenta(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [FATAL] [${appender}] - ${message}`));
    this.create(LogLevel.fatal, appender, message, detail);
  }

  /**
   * 创建日志
   * @param level 日志等级
   * @param appender 日志类别
   * @param message 日志消息
   * @param detail 日志详情
   */
  async create(level: LogLevel, appender: LogAppender, message: string, detail: string): Promise<LogEntity> {
    const logEntity = new LogEntity();
    logEntity.level = level;
    logEntity.appender = appender;
    logEntity.message = message;
    logEntity.detail = detail;

    return this.logRepository.save(logEntity);
  }

  /**
   * 批量删除活动日志
   * @param idList 日志编号列表
   */
  async deleteAll(idList?: number[]): Promise<DeleteResult> {
    if (idList && idList.length > 0) return this.logRepository.delete(idList);
    else {
      return this.logRepository.createQueryBuilder('logs').delete().execute();
    }
  }

  /**
   * 分页获取日志
   * @param pageIndex 页码
   * @param pageSize 页容量
   * @param sortType 升降序
   * @param level 日志级别
   * @param appender 日志类别
   * @param keyword 关键字
   */
  async findAndPaging(pageIndex: number, pageSize: number, sortType: SortType, start: Date, end: Date, level?: LogLevel, appender?: LogAppender, keyword?: string): Promise<[LogEntity[], number]> {
    return this.logRepository.findAndCount({
      where: Object.assign({ createdAt: Between(start, end) }, level ? { level } : {}, appender ? { appender } : {}, keyword ? { message: Like(`%${keyword}%`) } : {}),
      order: { createdAt: sortType },
      skip: pageIndex * pageSize,
      take: pageSize
    });
  }
}
